<?php

require_once(CONFIG_DIR . 'reg_shop_config.php');
require_once(LIB_DIR . 'api/general.php');
require_once(LIB_DIR . 'api/Snoopy.php');

$shopDAO = GetShopDAO();
$cityDAO = GetCityDAO();
$shopCategoryDAO = GetShopCategoryDAO();
$errmsg = GetMessageStack();

/* 关键数据存在session */
$shopURL = "";
$extShopID = "";
$platID = "";
$status = "";
$isMall = "";

/* 用户的提交数据 */
$shopName = "";
$nickName = "";
$logoURL = "";
$shopLocation = "";
$shopCategory = "";
$createdDate = "";
$shopDesc = "";

$city = "";
$province = "";

if (isset($_POST['action'])) {

    if ($_POST['action'] == 'addShop1') {
        ShowAddShopPage();
    } else if ($_POST['action'] == 'addShop2') {

        ProcessAddShop();
    }
} else {

    if (isset($_GET['shopURL']))
        $shopURL = $_GET['shopURL'];

    TransferTo('add_shop_1');
}

function ShowAddShopPage() {
    global $shopURL, $platID, $extShopID, $status,
    $shopName, $nickName, $logoURL, $shopLocation, $shopCategory, $createdDate, $shopDesc,
    $shopDAO, $cityDAO, $shopCategoryDAO, $errmsg, $city, $province;

    $snoopy = new Snoopy;
    $snoopy->agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    
    $shopURL = edp_db_input(trim($_POST['url']));
    $vcode = trim($_POST['vcode']);

    if (IsParaOK() == false) {
        TransferTo('add_shop_1');
        return;
    }

    /**
     * 根据输入的店铺URL检索平台，目前支持1：taobao 2:eachnet 3.paipai 4.youa，
     * 以后可以逐步增加平台，加在switch里（只限可以用二级域名创建店铺的网站)
     * platid：0为unknown; 1～99的为典型的c2c（淘宝，拍拍等）; 100为b2c ; 101～N 为分离出来的b2c（当当，卓越等）
     */
    $platID = CheckPlatform($shopURL); //检查shopURL是否属于可以用二级域名创建店铺的平台，不是的返回0

    switch ($platID) {
        case '0': {
                //平台为0没有附加表，根据url在shop_info里判断url是否已经存在。
                $shopID = $shopDAO->GetShopIDByURL($shopURL);

                if ($shopID) {
                    $errmsg->add('reg', "该店铺已添加，<a href=" . edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID") . ">点击查看</a>");

                    TransferTo('add_shop_1');
                    return;
                } else {
                    //状态5：可以显示店铺页面，但是不容许添加商品
                    //管理员审核 (转移到b2c(100),添加新的平台,不同url重复的店铺设置status为9)
                    //审核时候注意，要取正常的url为shopURL，不要带上用户的推广链接等后缀！
                    $status = ADDSHOP_STATUS_UNKOWNN_PLATFORM;
                    break;
                }
            }

        case '1'://taobao，platid是1。taobao店铺获取数据流程：根据html获取nick->根据nick通过API获取数据
        {
                require_once(LIB_DIR . 'api/taobao/Taoapi.php');

                $snoopy->fetch($shopURL);
                
                $html_content = $snoopy->results;

                $isTaobaoMall = CheckRegStatus($html_content, TAOBAO_MALL); //根据正则获取关键数据nickName,淘宝商城和普通店铺
                $nickName = ConvertEncoding(GetDataByRegx($html_content, $isTaobaoMall ? TAOBAO_MALL_NICK_NAME : TAOBAO_NICK_NAME), TAOBAO_ENCODING);

                if (!edp_is_empty_string($nickName)) {

                    $shopID = $shopDAO->GetShopIDByNick($nickName, $platID);

                    if ($shopID) {
                        $errmsg->add('reg', "该店铺已添加，<a href=" . edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID") . ">点击查看</a>");
                        TransferTo('add_shop_1');
                        return;
                    } else {

                        //根据nickName查询shop_info表，看shopID是否存在，shopID不存在的情况有2种：
                        //1.该店铺不存在，nickName则不会存在于shop_info表中，查询不到
                        //2.该店铺其实存在，但是由于nickName正则错误没有取到正确的值，导致查询不到
                        //对于情况2，会完成添加店铺的步骤，需要经常审核正则的正确性，通过用户报错和人工合并数据

                        $Taoapi = new Taoapi;
                        $Taoapi->method = 'taobao.shop.get';
                        $Taoapi->fields = 'sid,cid,nick,title,desc,bulletin,pic_path,created,modified';
                        $Taoapi->nick = $nickName;
                        $TaobaoData = $Taoapi->Send('get', 'xml')->getArrayData();

                        if (edp_is_empty_string($Taoapi->getErrorInfo())) {

                            $extShopID = $TaobaoData['shop']['sid']; //taobao平台的扩展id，作为shop_info_taobao的主键
                            $shopName = $TaobaoData['shop']['title'];
                            $createdDate = substr($TaobaoData['shop']['created'], 0, 10);
                            $shopDesc = $TaobaoData['shop']['desc'];
                            if (is_array($TaobaoData['shop']['desc'])) {
                                $shopDesc = $TaobaoData['shop']['desc'][0];
                            } else {
                                $shopDesc = $TaobaoData['shop']['desc'];
                            }
                            $shopCategory = $shopCategoryDAO->ConvertTaobaoShopCid($TaobaoData['shop']['cid']);  //把taobaoAPI的cid转换为本地的cid,	return 0 if no value

                            $shopLocation = $cityDAO->GetCityID(ConvertEncoding(GetDataByRegx($html_content, $isTaobaoMall ? TAOBAO_MALL_LOCATION : TAOBAO_LOCATION), TAOBAO_ENCODING)); //把正则获取的location称转换为本地的city id, return 0 if no value


                            $city = $cityDAO->GetCityNameSimple($shopLocation);
                            $provinceid = $cityDAO->GetProvinceIDByCityID($shopLocation);
                            if ($provinceid != 0)
                                $province = $cityDAO->GetCityNameSimple($provinceid);
                            else
                                $province = $city;


                            if ($isTaobaoMall) {
                                edp_setsession('isMall', '1');
                                $logoURL = TAOBAO_MALL_LOGO; //淘宝商城店铺统一logo
                            } else {
                                edp_setsession('isMall', '0');
                                if (isset($TaobaoData['shop']['pic_path']))
                                    $logoURL = TAOBAO_PIC_PREFIX . $TaobaoData['shop']['pic_path'];
                            }

                            $status = ADDSHOP_STATUS_SUCCESS;
                        } else {

                            $status = ADDSHOP_STATUS_MISS_TAOBAOAPI_DATA;
                        }
                    }
                } else {

                    //状态2：正则获取不到nickName，正则错误或者url为假，可以显示店铺页面，但是不容许添加商品
                    //管理员审核(对于不同url重复的店铺设置status为9,人工完善数据后设置status为1）
                    $status = ADDSHOP_STATUS_MISS_KEY_DATA;
                }
                break;
            }

        case '2'://eachnet平台，platid是2。eachnet店铺获取数据流程：根据html获取extShopId->判断是否存在->不存在继续根据html获取数据
        {
                $snoopy->fetch($shopURL);

                $html_content = $snoopy->results;

                $extShopID = GetEachnetShopID($html_content);

                if (!edp_is_empty_string($extShopID)) {
                    $shopID = $shopDAO->GetShopIDByExtID($extShopID, 'eachnet');

                    if ($shopID) {
                        $errmsg->add('reg', "该店铺已添加，<a href=" . edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID") . ">点击查看</a>");
                        TransferTo('add_shop_1');
                        return;
                    } else {
                        //查询shop_info_eachnet表，根据extShopID查询shopID是否存在,shopID不存在的情况有2种：
                        //1.该店铺不存在，extShopID则不会存在于shop_info_eachnet表中，查询不到
                        //2.该店铺其实存在，但是由于extShopID正则错误没有取到正确的值，导致查询不到
                        //对于情况2，会完成添加店铺的步骤，需要经常审核正则的正确性，通过用户报错和人工合并数据

                        $shopName = ConvertEncoding(GetDataByRegx($html_content, EACHNET_SHOP_NAME), EACHNET_ENCODING);
                        $nickName = ConvertEncoding(GetDataByRegx($html_content, EACHNET_NICK_NAME), EACHNET_ENCODING);
                        $createdDate = substr(GetDataByRegx($html_content, EACHNET_CREATED_DATE), 0, 10);
                        $logoURL = GetDataByRegx($html_content, EACHNET_LOGO_URL);
                        //$shopLocation $shopCategory $shopDesc

                        $status = ADDSHOP_STATUS_SUCCESS;

                        if (edp_is_empty_string($shopName) || edp_is_empty_string($nickName) ||
                                edp_is_empty_string($createdDate) || edp_is_empty_string($logoURL)) {

                            $status = ADDSHOP_STATUS_MISS_REG_DATA;
                        }
                    }
                } else {
                    //状态2：正则获取不到extShopID，正则错误或者url为假，可以显示店铺页面，但是不容许添加商品
                    //管理员审核（对于不同url重复的店铺设置status为9,人工完善数据设置status为1）
                    $status = ADDSHOP_STATUS_MISS_KEY_DATA;
                }
                break;
            }

        case '3'://paipai平台，platid是3。paipai店铺获取数据流程：根据html获取extShopId->判断是否存在->不存在继续根据html获取数据
        {
                $snoopy->fetch($shopURL);
                $html_content = $snoopy->results;

                $extShopID = GetPaipaiShopID($html_content);

                if (!edp_is_empty_string($extShopID)) {
                    $shopID = $shopDAO->GetShopIDByExtID($extShopID, 'paipai');
                    if ($shopID) {
                        $errmsg->add('reg', "该店铺已添加，<a href=" . edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID") . ">点击查看</a>");
                        TransferTo('add_shop_1');
                        return;
                    } else {
                        $nickName = $extShopID;
                        $shopName = ConvertEncoding(GetDataByRegx($html_content, PAIPAI_SHOP_NAME), 'GBK'); //PAIPAI_ENCODING);
                        //$shopLocation $shopCategory $createdDate $logoURL  $shopDesc

                        $status = ADDSHOP_STATUS_SUCCESS;

                        if (edp_is_empty_string($shopName) || edp_is_empty_string($nickName)) {
                            $status = ADDSHOP_STATUS_MISS_REG_DATA;
                        }
                    }
                } else {
                    $status = ADDSHOP_STATUS_MISS_KEY_DATA;
                }

                break;
            }

        case '4'://youa平台，platid是2。youa店铺获取数据流程：根据html获取extShopId->判断是否存在->不存在继续根据html获取数据
        {

                $snoopy->fetch($shopURL);
                $html_content = $snoopy->results;

                $extShopID = GetYouaShopID($html_content);

                if (!edp_is_empty_string($extShopID)) {
                    $shopID = $shopDAO->GetShopIDByExtID($extShopID, 'youa');
                    if ($shopID) {
                        $errmsg->add('reg', "该店铺已添加，<a href=" . edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID") . ">点击查看</a>");
                        TransferTo('add_shop_1');
                        return;
                    } else {

                        $shopName = ConvertEncoding(GetDataByRegx($html_content, YOUA_SHOP_NAME), 'GBK'); //YOUA_ENCODING);
                        $nickName = ConvertEncoding(GetDataByRegx($html_content, YOUA_NICK_NAME), 'GBK'); //YOUA_ENCODING);
                        $createdDate = substr(GetDataByRegx($html_content, YOUA_CREATED_DATE), 0, 10);
                        $logoURL = GetDataByRegx($html_content, YOUA_LOGO_URL);
                        //$shopLocation  $shopCategory $shopDesc

                        $status = ADDSHOP_STATUS_SUCCESS;

                        if (edp_is_empty_string($shopName) || edp_is_empty_string($nickName) ||
                                edp_is_empty_string($createdDate) || edp_is_empty_string($logoURL)) {
                            $status = ADDSHOP_STATUS_MISS_REG_DATA;
                        }
                    }
                } else {
                    $status = ADDSHOP_STATUS_MISS_KEY_DATA;
                }
                break;
            }

        default: {
                $status = ADDSHOP_STATUS_UNKOWNN_PLATFORM;
                break;
            }
    }

    edp_setsession('shopURL', $shopURL);
    edp_setsession('platID', $platID);
    edp_setsession('extShopID', $extShopID);
    edp_setsession('status', $status);

    TransferTo('add_shop_2');
}

function ProcessAddShop() {
    global $shopURL, $platID, $extShopID, $status, $isMall,
    $shopName, $nickName, $logoURL, $shopLocation, $shopCategory, $createdDate, $shopDesc,
    $shopDAO, $cityDAO, $shopCategoryDAO, $errmsg;


    $shopName = edp_db_input(trim($_POST['shopName']));
    $nickName = edp_db_input(trim($_POST['nickName']));
    $logoURL = edp_db_input(trim($_POST['logoURL']));
    $shopDesc = $_POST['shopDesc'];
    $createdDate = edp_db_input(trim($_POST['createdDate']));
    $shopLocation = $cityDAO->GetCityID(edp_db_input(trim($_POST['city'])));
    $shopCategory = edp_db_input(trim($_POST['shopCategory']));

    $shopURL = edp_getsession('shopURL');
    $platID = edp_getsession('platID');
    $extShopID = edp_getsession('extShopID');
    $status = edp_getsession('status');
    $userID = edp_getsession('userid');

    if (!edp_isset_session('shopURL') || !edp_isset_session('platID') || !edp_isset_session('extShopID') ||
            !edp_isset_session('status')) {

        $errmsg->add('reg', '错误请求,请重新输入');

        if (get_magic_quotes_gpc ()) {
            $shopDesc = stripslashes($shopDesc); //显示post后没有quote的在本页面
        }

        TransferTo('add_shop_1');
        return;
    }


    if (IsParaOK() == false) {
        if (get_magic_quotes_gpc ()) {
            $shopDesc = stripslashes($shopDesc); //显示post后没有quote的在本页面
        }
        TransferTo('add_shop_2');
        return;
    }


    $shopDesc = EdpFilterHtmlTag(edp_db_input(trim($shopDesc)));

    switch ($platID) {

        /*         * ****************************
         * 未知平台的店铺: 只插入shop_info,没有附加表
         * *************************** */
        case '0': {

                $shopID = $shopDAO->InsertCommonShopData($platID, $shopName, $shopURL, $logoURL,
                                $nickName, $createdDate, $shopLocation, $userID,
                                $status, $shopCategory, $shopDesc);

                break;
            }

        /*         * ***************************
         * taobao：插入shop_info和附加表shop_info_taobao（添加淘宝客链接）
         * ************************** */
        case '1': {
                require_once(LIB_DIR . 'api/taobao/Taoapi.php');


                $Taoapi = new Taoapi;
                $Taoapi->method = 'taobao.taobaoke.shops.convert';
                $Taoapi->fields = 'user_id,shop_title,click_url,commission_rate';
                $Taoapi->sids = $extShopID;
//				$Taoapi->nick = TAOBAOKE_ID;
                $Taoapi->pid = TAOBAOKE_ID;
                $TaobaokeData = $Taoapi->Send('get', 'xml')->getArrayData();


                if (edp_is_empty_string($Taoapi->getErrorInfo()) && !empty($TaobaokeData)) { //如果存在click_url,commissionURL肯定是自己的推广链接
                    $commissionURL = $TaobaokeData['taobaoke_shops']['taobaoke_shop']['click_url'];
                    $commissionRate = $TaobaokeData['taobaoke_shops']['taobaoke_shop']['commission_rate'];
                } else {

                    $commissionRate = '0';
                    $commissionURL = $shopURL;
                }
                
                if (edp_isset_session('isMall')) {
                    $isMall = edp_getsession('isMall');
                } else {
                    $isMall = '0';
                }

                $shopID = $shopDAO->InsertTaobaoShopData($platID, $shopName, $shopURL, $logoURL,
                                $nickName, $createdDate, $shopLocation, $userID,
                                $status, $shopCategory, $shopDesc, $extShopID, $commissionURL, $commissionRate, $isMall);
                edp_unset_session('isMall');
                break;
            }


        /*         * ****************************
         * eachnet: 插入shop_info和附加表shop_info_eachnet
         * *************************** */
        case '2': {

                $shopID = $shopDAO->InsertEachnetShopData($platID, $shopName, $shopURL, $logoURL,
                                $nickName, $createdDate, $shopLocation, $userID,
                                $status, $shopCategory, $shopDesc, $extShopID);

                break;
            }


        /*         * ***************************
         * paipai:插入shop_info和附加表shop_info_paipai
         * ************************** */
        case '3': {


                $shopID = $shopDAO->InsertPaipaiShopData($platID, $shopName, $shopURL, $logoURL,
                                $nickName, $createdDate, $shopLocation, $userID,
                                $status, $shopCategory, $shopDesc, $extShopID);

                break;
            }

        /*         * ***************************
         * youa:插入shop_info和附加表shop_info_youa
         * ************************** */
        case '4': {

                $shopID = $shopDAO->InsertYouaShopData($platID, $shopName, $shopURL, $logoURL,
                                $nickName, $createdDate, $shopLocation, $userID,
                                $status, $shopCategory, $shopDesc, $extShopID);


                break;
            }

        default: {

                break;
            }
    }


    edp_unset_session('shopURL');
    edp_unset_session('platID');
    edp_unset_session('extShopID');
    edp_unset_session('status');


    //status不等于 2 和5，更新 event , contribution, staticstic
    if ($shopID && !edp_is_empty_string($shopID) && $status != ADDSHOP_STATUS_MISS_KEY_DATA && $status != ADDSHOP_STATUS_UNKOWNN_PLATFORM) {
        //增加shop_count
        $userDAO = GetUserDAO();
        $userDAO->IncreaseAddShopCount($userID);

        //事件通知
        $para['sid'] = $shopID;
        $eventDispatcher = GetEventDispatcher();
        $eventDispatcher->Notify($userID, ADD_SHOP, $para);
    }

    edp_redirect(edp_href_link(PAGENAME_SHOP_INFO, "sid=$shopID"));
}

?>
